"""
测试运行脚本
"""
import os
import sys
import subprocess
import time
import shutil
from datetime import datetime

def parse_args():
    """解析命令行参数"""
    args = {}
    # 设置默认值
    args['env'] = 'dev'
    args['report'] = True
    args['markers'] = ''
    args['path'] = ''
    
    # 解析命令行参数
    for arg in sys.argv[1:]:
        if '=' in arg:
            key, value = arg.split('=', 1)
            if key.upper() == 'ENV':
                args['env'] = value.lower()
            else:
                args[key.lower()] = value
        elif arg.lower() == 'report':
            args['report'] = True
        elif arg.lower() == 'no-report':
            args['report'] = False
    
    return args

def run_tests(args):
    """运行测试"""
    # 设置环境变量
    os.environ['ENV'] = args['env']
    
    # 构建pytest命令
    cmd = ['pytest']
    
    # 添加测试路径
    if args['path']:
        cmd.append(args['path'])
    else:
        cmd.append('api_test_framework/tests')
    
    # 添加标记
    if args['markers']:
        cmd.append(f'-m {args["markers"]}')
    
    # 创建固定的报告目录（不使用时间戳）
    allure_report_dir = f'api_test_framework/reports/allure_{args["env"]}'
    html_report_dir = f'api_test_framework/reports/html_{args["env"]}'
    
    # 确保目录存在
    os.makedirs(allure_report_dir, exist_ok=True)
    os.makedirs(html_report_dir, exist_ok=True)
    
    # 添加Allure报告参数
    cmd.append(f'--alluredir={allure_report_dir}')
    
    # 添加HTML报告参数
    cmd.append(f'--html={html_report_dir}/report.html')
    cmd.append('--self-contained-html')
    
    # 添加详细输出
    cmd.append('-v')
    
    # 运行测试
    print(f"运行命令: {' '.join(cmd)}")
    result = subprocess.run(' '.join(cmd), shell=True)
    
    # 生成报告
    if args['report'] and result.returncode in [0, 1]:
        # 生成Allure报告
        print(f"生成Allure报告...")
        html_allure_dir = f'api_test_framework/reports/allure_html_{args["env"]}'
        
        # 确保目录存在
        os.makedirs(html_allure_dir, exist_ok=True)
        
        # 生成Allure HTML报告
        subprocess.run(f'allure generate {allure_report_dir} -o {html_allure_dir} --clean', shell=True)
        
        # 创建index.html文件，提供报告链接
        create_index_html(args['env'], html_report_dir, html_allure_dir)
        
        # 复制资源文件到正确位置，确保nginx可以正确访问
        ensure_report_assets(html_report_dir, html_allure_dir)
        
        # 打开HTML报告
        print(f"HTML报告已生成: {html_report_dir}/report.html")
        print(f"Allure HTML报告已生成: {html_allure_dir}/index.html")
        print(f"报告索引页: api_test_framework/reports/index.html")
        
        # 尝试自动打开报告
        try:
            if os.name == 'nt':  # Windows
                os.system(f'start api_test_framework/reports/index.html')
            elif os.name == 'posix':  # Linux/Mac
                os.system(f'open api_test_framework/reports/index.html')
        except:
            pass
    
    return result.returncode

def ensure_report_assets(html_report_dir, html_allure_dir):
    """确保报告的资源文件可以被正确访问"""
    # 确保HTML报告的资源文件可以被nginx访问
    assets_dir = os.path.join(html_report_dir, 'assets')
    if os.path.exists(assets_dir):
        # 设置assets目录的权限为755
        try:
            if os.name != 'nt':  # 非Windows系统
                os.chmod(assets_dir, 0o755)
                for root, dirs, files in os.walk(assets_dir):
                    for d in dirs:
                        os.chmod(os.path.join(root, d), 0o755)
                    for f in files:
                        os.chmod(os.path.join(root, f), 0o644)
        except Exception as e:
            print(f"设置权限时出错: {str(e)}")
    
    # 确保Allure报告的资源文件可以被nginx访问
    for root, dirs, files in os.walk(html_allure_dir):
        try:
            if os.name != 'nt':  # 非Windows系统
                for d in dirs:
                    os.chmod(os.path.join(root, d), 0o755)
                for f in files:
                    os.chmod(os.path.join(root, f), 0o644)
        except Exception as e:
            print(f"设置权限时出错: {str(e)}")

def create_index_html(env, html_report_dir, html_allure_dir):
    """创建索引HTML文件，提供报告链接"""
    index_content = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>API测试报告 - {env.upper()} 环境</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 800px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #333;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }}
        .report-link {{
            display: block;
            margin: 15px 0;
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            font-weight: bold;
        }}
        .report-link:hover {{
            background-color: #45a049;
        }}
        .timestamp {{
            color: #666;
            font-style: italic;
            margin-bottom: 20px;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>API测试报告 - {env.upper()} 环境</h1>
        <div class="timestamp">生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</div>
        
        <a href="{html_report_dir.replace('api_test_framework/reports/', '')}/report.html" class="report-link">查看Pytest HTML报告</a>
        <a href="{html_allure_dir.replace('api_test_framework/reports/', '')}/index.html" class="report-link">查看Allure HTML报告</a>
    </div>
</body>
</html>
"""
    
    # 创建索引文件
    with open('api_test_framework/reports/index.html', 'w', encoding='utf-8') as f:
        f.write(index_content)
    
    # 设置索引文件的权限为644，确保nginx可以读取
    try:
        if os.name != 'nt':  # 非Windows系统
            os.chmod('api_test_framework/reports/index.html', 0o644)
    except Exception as e:
        print(f"设置权限时出错: {str(e)}")

if __name__ == '__main__':
    args = parse_args()
    print(f"开始运行API测试，环境: {args['env']}")
    start_time = time.time()
    
    try:
        exit_code = run_tests(args)
        
        end_time = time.time()
        duration = end_time - start_time
        print(f"测试完成，耗时: {duration:.2f}秒")
        
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("测试被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"测试运行出错: {str(e)}")
        sys.exit(1) 